package com.example.controller.system;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.example.api.FileUploadApi;
import com.example.pojo.SystemUser;
import com.example.utils.RestfulResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;


/**
 * @author cbk
 * @date 2017/12/23
 */
@Controller
@RequestMapping(value = "/file")
public class SystemFileController{

    private Logger logger=Logger.getLogger(SystemFileController.class);

    @Autowired
    private FileUploadApi fileUploadApi;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public RestfulResult upload(MultipartFile file,HttpSession session){
        SystemUser systemUser=(SystemUser) session.getAttribute("user");
        logger.info("文件:"+file.getName()+","+file.getOriginalFilename()+","+file.getContentType());
        if(file.isEmpty()){
            return RestfulResult.warning(-10,"文件不能为空");
        }

        //上传文件到阿里云
        int code=200;
        String message="";
        int id=0;
        try {
            id=fileUploadApi.uploadFile(file,systemUser.getId());
        } catch (OSSException oe){//服务器异常
            logger.info("Caught an OSSException, which means your request made it to OSS,but was rejected with an error response for some reason.");
            logger.info("Error Message: " + oe.getErrorMessage());
            logger.info("   Error Code: " + oe.getErrorCode());
            logger.info("   Request ID: " + oe.getRequestId());
            logger.info("      Host ID: " + oe.getHostId());
            code=-10;
            message="服务器端错误";
        } catch (IOException ie){//
            code=-20;
            message="文件上传时发生IO异常";
        } catch (ClientException ce){//网络异常
            code=-30;
            message="客户端异常";
        }
        return new RestfulResult(code,message,"id",id);
    }
}
